package cn.edu.zafu.bigdata.x.wupeng.j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpServer1 {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(6666); // 监听指定端口
        System.out.println("server is running...");
        for (;;) {
            Socket sock = ss.accept();
            System.out.println("connected from " + sock.getRemoteSocketAddress());
            Thread t = new Handler(sock);
            t.start();
        }
    }
}
class Handler extends Thread {
    Socket sock;
    Handler(Socket sock) {
        this.sock = sock;
    }
    public void run() {
        try {
            try(InputStream input = sock.getInputStream()){
                try(OutputStream output = sock.getOutputStream()){
                    handle(input,output);
                }
            }
            sock.close();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void handle(InputStream input, OutputStream output) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
        writer.write("我是3058号服务器，很高兴为你服务。");
        writer.newLine();
        writer.flush();
        while (true){
            String line = reader.readLine();
            writer.write(">>>"+line);
            writer.newLine();
            writer.flush();
            System.out.println("Client:"+line);
            if ("bye".equalsIgnoreCase(line)){
                System.out.println("Client Disconnected");
                break;
            }
        }
    }
}
